package se.rkrantz.simpleraid.service.openid;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.openid.OpenIDAttribute;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import se.rkrantz.simpleraid.hibernate.dao.UserDao;
import se.rkrantz.simpleraid.hibernate.domain.User;
import se.rkrantz.simpleraid.web.controller.profile.ProfileController;


public class OpenIdAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	private final Logger logger = LoggerFactory.getLogger(OpenIdAuthenticationFailureHandler.class);
	@Autowired private UserDao userDao;
	
	public User registerOpenIdUser(String username, OpenIDAuthenticationToken token) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(new Md5PasswordEncoder().encodePassword("lol", null)); // TODO fix some auto-generated password-thingy
		user.setRoles(Collections.singletonList("ROLE_USER"));
		if (user != null) {
			for (OpenIDAttribute a : token.getAttributes()) {
				logger.debug("OpenIDAttribute: {} => {}", a.getName(), a.getValues().get(0));
				if ("email".equals(a.getName())) {
					user.setEmail(a.getValues().get(0));
					break;
				}
			}
		}
		if (user.getEmail() == null) {
			user.setEmail("--");
		}
			
		user.setSignupDate(new DateTime());
		userDao.save(user);
		
		return user;
	}
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
		
		if (exception instanceof UsernameNotFoundException) {
			OpenIDAuthenticationToken token = (OpenIDAuthenticationToken)exception.getAuthentication();
			String username = exception.getExtraInformation().toString();
			if (registerOpenIdUser(username, token) != null) {
				SecurityContextHolder.getContext().setAuthentication(token);
				RedirectStrategy rs = new DefaultRedirectStrategy();
				rs.sendRedirect(request, response, "/index.html");
				return;
			}
		}
		super.onAuthenticationFailure(request, response, exception);
	}

}
